<?php
/**
 * --------------------------------------------------------------
 * 图表类
 * Author: zd <kfzphp@126.com>
 * Date: 2018-06-01
 * Project: kfzphp.com
 * --------------------------------------------------------------
 */

if(APP_DEBUG) {
    ini_set("display_errors", "On");
    error_reporting(E_ALL);
}

class KfzChart
{
    /**
     * 初始化
     * @author zd <kfzphp@126.com>
     * @since  2018-05-10
     */
    public function __construct()
    {

    }

    /**
     * 生成统计图
     * @author zd <kfzphp@126.com>
     * @since  2018-05-10
     * @param  [type]     $data [图表数据数组]
     * @return [type]           [description]
     */
    public function jpgraph($data)
    {
        // 判断数据
        if(empty($data)) {
            exit('Chart data empty');
        }

        // 纯文本的形式
        header("Content-type: text/plain; charset=utf-8");

        // 设置图表宽度
        $width = !empty($data['width']) ? $data['width'] : 800;
        // 设置图表高度
        $height = !empty($data['height']) ? $data['height'] : 500;
        // 设置主标题
        $title = !empty($data['title']) ? $data['title'] : '图表数据';
        // 设置横标题
        $xtitle = !empty($data['xtitle']) ? $data['xtitle'] : 'x';
        // 设置竖标题
        $ytitle = !empty($data['ytitle']) ? $data['ytitle'] : 'y';
        // 设置横标题列表
        $xdata = $data['xdata'];
        // 设置竖图表数据
        $ydata = $data['ydata'];

        // 实例化类
        include_once VENDOR_PATH . '/jpgraph/jpgraph.php';
        include_once VENDOR_PATH . '/jpgraph/jpgraph_bar.php';

        // 创建图表，这两个参数总是需要的
        $graph = new Graph($width, $height);
        $graph->SetScale('textlin');

        // 添加一个阴影
        $graph->SetShadow();

        // 调整边距一点，为标题留出更多空间
        $graph->SetMargin(60,30,30,60);

        // 创建一个条形图
        $bplot = new BarPlot($ydata);

        // 调整填充颜色
        $bplot->SetFillColor('orange');
        $graph->Add($bplot);

        // 设置值显示
        $bplot->value->Show(); //显示值
        $bplot->value->SetFont(FF_SIMSUN,FS_BOLD,10); //显示字体大小
        // $bplot->value->SetAngle(90); //显示角度
        // $bplot->value->SetFormat('%0.2f'); //显示格式 0.2f:精确到小属数点后2位
        $bplot->value->SetFormat('%d ');

        // 设置标题
        $graph->title->Set(my_iconv($title));
        $graph->xaxis->title->Set(my_iconv($xtitle));
        $graph->yaxis->title->Set(my_iconv($ytitle));

        // 设置标签
        if($xdata) {
            $lbl = array();
            foreach ($xdata as $k => $v) {
                $lbl[] = my_iconv($v);
            }
            $graph->xaxis->SetTickLabels($lbl);
            $graph->xaxis->SetFont(FF_SIMSUN,FS_BOLD);
        }

        // X轴对齐标签
        // $graph->xaxis->SetLabelAlign('right','center','right');

        // Y轴对齐标签
        // $graph->yaxis->SetLabelAlign('center','bottom');

        $graph->title->SetFont(FF_SIMSUN,FS_BOLD);
        $graph->yaxis->title->SetFont(FF_SIMSUN,FS_BOLD);
        $graph->xaxis->title->SetFont(FF_SIMSUN,FS_BOLD);

        // 显示图表
        $graph->Stroke();
    }
}